import datetime
import os
import time
import traceback
import evdev
import threading
import requests
import pickle
from led import red_on, green_off, red_off, green_on
from utils import localInfo, keymap
import voice

realCode = ''
startTime = ''
endTime = ''
Mode = 0
local_ip, local_mac = localInfo()
while len(local_ip) == 0:
    local_ip, local_mac = localInfo()
    time.sleep(1)
print(local_ip, local_mac)
baseURL = "https://zhanhuatech.net"
# baseURL = "http://192.168.3.102"

def login(username, password):
    try:
        data = requests.post(baseURL + "/user/piLogin", data={
            'id': username,
            'password': password
        }, timeout=0.5).json()
        print(data)
        if data['code'] == 200:
            token = data['data']['jwtToken']
            data = requests.post(baseURL + "/station/clientAdd", data={
                'stationIp': local_ip[0],
                'stationMac': local_mac[0],
            }, headers={
                "Authorization": "Bearer " + token,
            }).json()
            print(data)
            if data['code'] == 200:
                red_off()
                green_on()
                stationId = data['data']
                return [token, stationId]
    except Exception as e:
        print('error:' + username + ":" + password)
        traceback.print_exc()
        return None


class Device:
    def __init__(self):
        self.token = None
        self.stationId = None
        self.username = None
        self.password = None
        self.Mode = 0

    def load(self, path='device.ini'):
        try:
            f = open(path, 'rb')
            res = pickle.load(f)
            f.close()
            return res
        except:
            return Device()

    def save(self, path='device.ini'):
        f = open(path, 'wb')
        pickle.dump(self, f)
        f.close()
        # os.system("sync")#写入

    def testLogin(self):
        if self.token:
            token, stationId = login(self.username, self.password)
            if token:
                self.token = token
                self.stationId = stationId
                self.save()


usbs = list()
device = Device()


def push(CODE):
    print(CODE)
    # if CODE == "10000007":
    #     CODE = "LOGIN:hcc:2a10YTwYKstCP80WwikVOWvmUubJFEooQPcmA7aVUOgUjOcOVAxNSpYdm"
    global device
    CODE = CODE.replace(';', ':')
    print('push:' + CODE)
    global realCode
    global startTime
    global endTime
    CODE = CODE.upper()
    if CODE == "CMD:CLEAR":
        os.remove("device.ini")
        os.system("systemctl restart orange")
        print("clear")
        return
    if CODE.startswith("LOGIN:"):
        if local_ip[0]:
            info = CODE.split(':')
            if len(info) != 3:
                return
            token, stationId = login(info[1], info[2])
            if token:
                device.token = token
                device.stationId = stationId
                device.username = info[1]
                device.password = info[2]
                device.save()
                return
    if CODE == "SWITCH:0":
        device.Mode = 0
        device.save()
        voice.mode0()
        return
    elif CODE == "SWITCH:1":
        device.Mode = 1
        device.save()
        voice.mode1()
        return

    if device.token is None:
        print("未登录")
    if device.Mode == 0:
        data = requests.post(baseURL + "/goods/add", data={
            'id': CODE,
            'station_id': device.stationId
        }, headers={
            "Authorization": "Bearer " + device.token,
        }).json()
        data = data.get('data')
        error = data.get('error', False)
        if error:
            voice.error()
        print(data)
    elif device.Mode == 1:
        if realCode == '' or realCode != CODE:
            realCode = CODE
            startTime = datetime.datetime.now()
        elif realCode == CODE:
            endTime = datetime.datetime.now()
            data = requests.post(baseURL + "/goods/modeOneAdd", data={
                'id': realCode,
                'station_id': device.stationId,
                'startTime': startTime,
                'endTime': endTime,
            }, headers={
                "Authorization": "Bearer " + device.token,
            }).json()
            data = data.get('data')
            error = data.get('error', False)
            if error:
                voice.error()
            realCode = ''
            print(data)



def init():
    try:
        red_on()
        green_off()
        global device
        device = device.load()
        # device.testLogin()
    except:
        print("init error")


class USBServer(threading.Thread):
    def __init__(self, myUsb):
        super().__init__()
        self.myUsb = myUsb

    def run(self):
        try:
            buf = ''
            for event in self.myUsb.async_read_loop():
                # key_up= 0 key_down= 1 key_hold= 2
                if event.type == evdev.ecodes.EV_KEY and event.value == 1:
                    kv = evdev.events.KeyEvent(event)
                    # 本次修改的地方, 把事件映射到字符表
                    if kv.scancode == evdev.ecodes.KEY_ENTER:
                        try:
                            push(buf)
                        except:
                            print("push error")
                            voice.offline()
                        buf = ''
                    else:
                        buf += keymap.get(kv.keycode)
        except Exception as e:
            global usbs
            usbs.remove(self.myUsb)
            print("---异常---：", e)


class UsbSearch(threading.Thread):
    def __init__(self):
        super().__init__()

    def run(self):
        while True:
            port_list = [evdev.InputDevice(path) for path in evdev.list_devices()]
            for i in port_list:
                if i not in usbs:
                    usbs.append(i)
                    USBServer(i).start()
            time.sleep(3)


if __name__ == '__main__':
    voice.power_on()
    init()
    u = UsbSearch()
    u.start()
    u.join()
